//
//  JCDropTableViewController.m
//  JCDropTableView
//
//  Created by Guo.JC on 17/6/29.
//  Copyright © 2017年 coollang. All rights reserved.
//

#import "JCDropTableViewController.h"
#import "JCDropLeftCell.h"
#import "JCDropRightCell.h"
#import <pop/pop.h>


@interface JCDropTableViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *popView;
@property (weak, nonatomic) IBOutlet UIView *backGroundView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *leftLabel;
@property (weak, nonatomic) IBOutlet UIImageView *leftImageView;
@property (weak, nonatomic) IBOutlet UILabel *rightLabel;
@property (weak, nonatomic) IBOutlet UIImageView *rightImageView;
@property (weak, nonatomic) IBOutlet UITextField *inputTextFeild;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *conformBtn;
@property (weak, nonatomic) IBOutlet UITableView *leftTableView;
@property (weak, nonatomic) IBOutlet UIView *leftCoverView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftTableViewHeightContraint;
@property (weak, nonatomic) IBOutlet UITableView *rightTableView;
@property (weak, nonatomic) IBOutlet UIView *rightCoverView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightTableViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *popTopConstraint;
@property (assign, nonatomic) BOOL isTapLeft;
@property (assign, nonatomic) BOOL isTapRight;
@property (assign, nonatomic) LeftHandType selectedHandType;
@property (assign, nonatomic) NSInteger selectedRow;
@end

@implementation JCDropTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUp];
    [self addKyBoardNotice];
    _selectedHandType = _selectedRow = -1;
    
    [self.cancelBtn setTitle:NSLocalizedString(@"Cancel", nil) forState:UIControlStateNormal];
    [self.conformBtn setTitle:NSLocalizedString(@"Save", nil) forState:UIControlStateNormal];
}

- (void)addKyBoardNotice{
    //监听当键盘将要出现时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)removeKeyBoardNotice{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

//当键盘出现
- (void)keyboardWillShow:(NSNotification *)notification{
    //获取键盘的高度
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    int height = keyboardRect.size.height;
    
    _popTopConstraint.constant = [UIScreen mainScreen].bounds.size.height - height - 230 - 64;
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}
//当键退出
- (void)keyboardWillHide:(NSNotification *)notification{
    //获取键盘的高度
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [value CGRectValue];
//    int height = keyboardRect.size.height;
    _popTopConstraint.constant = 0.5*[UIScreen mainScreen].bounds.size.height - 115 - 64;
    [UIView animateWithDuration:.5 animations:^{
        [self.view layoutIfNeeded];
    }];
}

//- (void)textFieldDidChange:(UITextField *)textField
//{
//    if (textField == self.inputTextFeild) {
//        if (textField.text.length > 4) {
//            textField.text = [textField.text substringToIndex:4];
//        }
//    }
//}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    if (textField.text.length == 4) {
//        return NO;
//    }else{
//        return YES;
//    }
//}

- (void)presentView{
    _popTopConstraint.constant = 0.5*[UIScreen mainScreen].bounds.size.height - 115 - 64;
    [UIView animateWithDuration:.8
                          delay:0
         usingSpringWithDamping:.5
          initialSpringVelocity:20
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [self.view layoutIfNeeded];
                     } completion:nil];
}

///取消
- (IBAction)cancelAction:(UIButton *)sender {
    [_inputTextFeild resignFirstResponder];
    POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha];
    anim.fromValue = @(1.0);
    anim.toValue = @(0.0);
    anim.duration = 0.5;
    [self.view pop_addAnimation:anim forKey:@"alpha"];
    [anim setCompletionBlock:^(POPAnimation *animation, BOOL complete) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        if (self.dismissBlock) {
            self.dismissBlock(NO);
        }
    }];
}

///确认
- (IBAction)conformAction:(UIButton *)sender {
    
    //判断是否有选择则类型、是否有输入名字
    if (_inputTextFeild.text.length <= 0 ||
        _selectedRow == -1 ||
        _selectedHandType == LeftHandTypeUnknow) {
        NSString *message;
        if ([_inputTextFeild.text isEqualToString:@""] || _inputTextFeild.text == nil) {
            message = NSLocalizedString(@"Please input the template name", @"请输入模板名字");
        }else if (_selectedHandType == LeftHandTypeUnknow){
            message = NSLocalizedString(@"Fore&Back hand", @"请选择正反手");
        }else if (_selectedRow == -1){
            message = NSLocalizedString(@"Choose the type", @"请选择类型");
        }
        [self.hud showString:message dimissAfterSecond:2];
        return;
    }else{
        NSString *name = _inputTextFeild.text;
        RLMResults *temp = [[YFThreeDTemplate getCurrentUserAllCustomTemplateModels] objectsWhere:@"name == %@",name];
        if (temp.count > 0) {
            YFLog(@"存在同名模板");
             [self.hud showString:[NSString stringWithFormat:NSLocalizedString(@"%@ already exists,please input again", nil),name] dimissAfterSecond:2];
            return;
        }
//        else if (name.length > 15){
//            YFLog(@"名字过长");
//            [self.hud showString:@"模板名称不能大于15个字" dimissAfterSecond:2];
//            return;
//        }
    }
    
    [_inputTextFeild resignFirstResponder];
    if (self.delegate && [self.delegate respondsToSelector:@selector(conformActionForInputText:selectedIndexPath:)]) {
        [self.delegate conformActionForInputText:_inputTextFeild.text selectedIndexPath:[NSIndexPath indexPathForRow:_selectedRow inSection:_selectedHandType]];
    }
    POPBasicAnimation *anim = [POPBasicAnimation animationWithPropertyNamed:kPOPViewAlpha];
    anim.fromValue = @(1.0);
    anim.toValue = @(0.0);
    anim.duration = 0.5;
    
    [self.view pop_addAnimation:anim forKey:@"alpha"];
    [anim setCompletionBlock:^(POPAnimation *animation, BOOL complete) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
        if (self.dismissBlock) {
            self.dismissBlock(YES);
            self.dismissBlock = nil;
        }
    }];
}

- (void)setUp{
//    [_inputTextFeild addTarget:self
//                        action:@selector(textFieldDidChange:)
//              forControlEvents:UIControlEventEditingChanged];
    
    _backGroundView.layer.cornerRadius = 5;
    _backGroundView.layer.masksToBounds = YES;
    
    _inputTextFeild.layer.borderWidth =
    _rightLabel.layer.borderWidth =
    _leftLabel.layer.borderWidth = 1;
    
    _inputTextFeild.layer.borderColor =
    _rightLabel.layer.borderColor =
    _leftLabel.layer.borderColor = [UIColor colorWithRed:208/256.0 green:211/256.0 blue:219/256.0 alpha:1].CGColor;
    
    _inputTextFeild.layer.cornerRadius =
    _rightLabel.layer.cornerRadius =
    _leftLabel.layer.cornerRadius = 3;
    
    _inputTextFeild.layer.masksToBounds =
    _rightLabel.layer.masksToBounds =
    _leftLabel.layer.masksToBounds = YES;
    
    [_leftTableView registerClass:[JCDropLeftCell class] forCellReuseIdentifier:@"JCDropLeftCell"];
    [_rightTableView registerClass:[JCDropRightCell class] forCellReuseIdentifier:@"JCDropRightCell"];
    
    _leftCoverView.layer.shadowColor = [UIColor grayColor].CGColor;
    _leftCoverView.layer.shadowOffset = CGSizeMake(-6, 6);
    _leftCoverView.layer.shadowOpacity = 1;
    
    _rightCoverView.layer.shadowColor = [UIColor grayColor].CGColor;
    _rightCoverView.layer.shadowOffset = CGSizeMake(-6, 6);
    _rightCoverView.layer.shadowOpacity = 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == _leftTableView) {
        return 2;
    }else{
        if (self.dataSource == nil || ![self.dataSource respondsToSelector:@selector(numberOfRowsInHandType:)]) {
            NSCAssert(nil, @"未设置dataSource、未实现代理方法-JCDropTableViewController");
            return 0;
        }else{
            return [self.dataSource numberOfRowsInHandType:_selectedHandType];
        }   
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell;
    if (tableView == _leftTableView) {
        NSArray *titles = @[@"Forehand",@"Backhand"];
        cell = [tableView dequeueReusableCellWithIdentifier:@"JCDropLeftCell" forIndexPath:indexPath];
        [((JCDropLeftCell *)cell) showText:titles[indexPath.row]];
    }else{
        cell = [tableView dequeueReusableCellWithIdentifier:@"JCDropRightCell" forIndexPath:indexPath];
        [((JCDropRightCell *)cell) showText:[self.dataSource textForCellInHandType:_selectedHandType row:indexPath.row]];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UILabel *label;
    for (UILabel *view in [tableView cellForRowAtIndexPath:indexPath].subviews) {
        if ([view isKindOfClass:[UILabel class]] && view.tag == 10086) {
            label = view;
        }
    }
    if (tableView == _leftTableView) {
        _leftLabel.text = label.text;
        if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedIndexPath:)]) {
            [self.delegate didSelectedIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]];
        }
        _isTapLeft = YES;
        [self leftTapAction:nil];
        _selectedHandType = indexPath.row;
        [_rightTableView reloadData];
    }else{
        _rightLabel.text = label.text;
        if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectedIndexPath:)]) {
            [self.delegate didSelectedIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:1]];
        }
        _isTapRight = YES;
        [self rightTapAction:nil];
        _selectedRow = indexPath.row;
    }
}

///选择正反手
- (IBAction)leftTapAction:(UITapGestureRecognizer *)sender {
    UIColor *backColor;
    if (_isTapLeft) {
        _isTapLeft = NO;
        _leftTableViewHeightContraint.constant = 0;
        backColor = [UIColor clearColor];
        
    }else{
        _isTapLeft = YES;
        _leftTableViewHeightContraint.constant = 200;
        backColor = [UIColor colorWithRed:208/256.0 green:211/256.0 blue:219/256.0 alpha:1];
    }
    [UIView animateWithDuration:.8
                          delay:0
         usingSpringWithDamping:.5
          initialSpringVelocity:20
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [self.view layoutIfNeeded];
                         _leftImageView.transform = CGAffineTransformRotate(_leftImageView.transform, M_PI);
                         _leftLabel.backgroundColor = backColor;
                     } completion:nil];
}

///选择球类型
- (IBAction)rightTapAction:(UITapGestureRecognizer *)sender {
    if (_selectedHandType == LeftHandTypeUnknow) {
        return;
    }
    UIColor *backColor;
    if (_isTapRight) {
        _isTapRight = NO;
        _rightTableViewHeightConstraint.constant = 0;
        backColor = [UIColor clearColor];
    }else{
        _isTapRight = YES;
        _rightTableViewHeightConstraint.constant = 200;
        backColor = [UIColor colorWithRed:208/256.0 green:211/256.0 blue:219/256.0 alpha:1];
    }
    [UIView animateWithDuration:.8
                          delay:0
         usingSpringWithDamping:.5
          initialSpringVelocity:20
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         [self.view layoutIfNeeded];
                         _rightImageView.transform = CGAffineTransformRotate(_rightImageView.transform, M_PI);
                         _rightLabel.backgroundColor = backColor;
                     } completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [_inputTextFeild resignFirstResponder];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    NSLog(@"释放JCDrop");
    [self removeKeyBoardNotice];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
